const path = require('path')
const fs = require('fs')
const Client = require('ssh2-sftp-client')
const CLI = require('clui')
const Spinner = CLI.Spinner
const sftp = new Client()

const targetDir = '/home/web/project/webs/admin'
const resourceDir = path.join(__dirname, '/admin')

const cacheFiles = []
const start = new Date()
const listFile = (dir) => {
  return new Promise(async(resolve) => {
    let temp = await sftp.list(dir)
    temp = temp.map(res => {
      if (res.type === 'd') {
        return listFile(dir + '/' + res.name)
      } else {
        return new Promise(resolve => {
          cacheFiles.push({ ...res, path: dir + '/' + res.name })
          resolve()
        })
      }
    })
    resolve(Promise.all(temp))
  })
}
const listFileLocal = (dir) => {
  let arr = []
  const temp = fs.readdirSync(dir)
  let lastPath = dir.split('/').reverse()
  lastPath = lastPath[0] + '/'
  temp.forEach(item => {
    const target = dir + '/' + item
    if (fs.statSync(target).isFile()) {
      arr.push(lastPath + path.basename(target))
    } else {
      arr = arr.concat(listFileLocal(target))
    }
  })
  return arr
}
const loading = {
  loading: '',
  start(msg) {
    this.loading = new Spinner(msg, ['⣾', '⣽', '⣻', '⢿', '⡿', '⣟', '⣯', '⣷'])
    this.loading.start()
  },
  end(msg) {
    this.loading.stop()
    console.log(msg)
  }
}
loading.start('部署开始: 链接服务器')
sftp.connect({
  host: '129.204.187.85',
  port: '22',
  username: 'web',
  password: 'xinyuan_20200202'
}).then(() => {
  loading.end('服务器链接成功!')
  loading.start('查询缓存文件')
  return listFile(targetDir + '/static')
}).then(() => {
  loading.end('查询缓存文件完毕!')
  loading.start('上传打包文件')
  return sftp.uploadDir(resourceDir, targetDir)
}).then(() => {
  loading.end('上传打包文件完毕!')
  loading.start('清除缓存文件')
  const localFiles = listFileLocal(resourceDir + '/static')
  let diff = cacheFiles.filter(item => {
    const isIn = localFiles.find(name => item.path.indexOf(name) !== -1)
    return !isIn
  })
  diff = diff.map(item => sftp.delete(item.path))
  return Promise.all(diff)
}).then(res => {
  loading.end(`共清除${res.length}个文件,清除缓存文件完毕!`)
  const end = new Date()
  const duration = (end - start) / 1000
  console.log(`部署成功!耗费${duration}s`)
  return sftp.end()
}).catch(err => {
  console.log(err, 'catch error')
  console.log('部署失败')
  return sftp.end()
})
